package com.change.service.article;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.change.core.page.Page;
import com.change.dto.req.QueryArticleInfoReq;
import com.change.dto.req.SaveArticleInfoReq;
import com.change.dto.resp.QueryArticleInfoResp;
import com.change.entity.article.ArticleInfo;
import com.change.mapper.article.ArticleInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 坏孩子是你啊
 * @date 2022-07-24
 */
@Slf4j
@Service
public class ArticleInfoService extends ServiceImpl<ArticleInfoMapper, ArticleInfo> {
    private final ArticleInfoMapper articleInfoMapper;

    public ArticleInfoService(ArticleInfoMapper articleInfoMapper) {
        this.articleInfoMapper = articleInfoMapper;
    }

    public Page<List<QueryArticleInfoResp>> getPage(Page page, QueryArticleInfoReq req) {
        page.offset();
        List<QueryArticleInfoResp> records = this.articleInfoMapper.pageArticle(page,req);
        page.setRecords(records);
        long total = this.articleInfoMapper.pageArticleTotal(req);
        page.setTotal(total);
        return page;
    }

    public QueryArticleInfoResp detail(Integer id) {
        QueryArticleInfoResp resp = this.articleInfoMapper.detailArticleById(id);
        return resp;
    }

    @Transactional(rollbackFor = Exception.class)
    public ArticleInfo save(SaveArticleInfoReq req) {
        ArticleInfo articleInfo = new ArticleInfo();
        BeanUtil.copyProperties(req, articleInfo);
        this.articleInfoMapper.insert(articleInfo);
        return articleInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    public ArticleInfo update(SaveArticleInfoReq req) {
        ArticleInfo articleInfo = new ArticleInfo();
        BeanUtil.copyProperties(req, articleInfo);
        this.articleInfoMapper.updateById(articleInfo);
        return articleInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer delete(Integer id) {
        this.articleInfoMapper.deleteById(id);
        return 0;
    }
}
